package com.faf.ui;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.faf.bean.Comment;
import com.faf.dao.impl.CommentDaoImpl;
import com.faf.dao.impl.OrdersDaoImpl;
import com.faf.dao.impl.StoreDaoImpl;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class TodoComment
 */
@WebServlet("/TodoComment")
public class TodoComment extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TodoComment() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int action = Integer.parseInt(request.getParameter("action").toString());
		String orderNumber = request.getParameter("order");
		
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter ajaxIo = response.getWriter();
		JSONObject jsonObject = new JSONObject();  
		CommentDaoImpl commentDao = new CommentDaoImpl();
		
		if(action == 0) {
			// 订单评价状态
			Comment comment = null;
			try {
				comment = commentDao.getCommentByOrderNumber(orderNumber);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jsonObject.put("state", null != comment);
			if(null != comment) {
				jsonObject.put("contect", comment.getCommentContext());
				jsonObject.put("score", comment.getCommentScore());
			}
		}
		else if(action == 1) {
			double score = Double.parseDouble(request.getParameter("score").toString());
			String contect = request.getParameter("contect").toString();
			// 新的评价
			System.out.println("新的评价");
			
			OrdersDaoImpl ordersDao = new OrdersDaoImpl();
			int storeId = 0;
			
			try {
				storeId = ordersDao.getOrderByOrderNumber(orderNumber).getStoreId();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				commentDao.newComment(
						Integer.parseInt(request.getSession().getAttribute("id").toString()),
						orderNumber, 
						contect, 
						score,
						storeId);
			} catch (NumberFormatException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			jsonObject.put("res", true);
		}
        
		ajaxIo.write(jsonObject.toString());
	}

}
